import jieba
import json

# 检查是否有短语检索要求
# 短语检索：用中文双引号括起来的内容，要求必须出现，并且是以短语出现在标题或者正文中
def searchPhrase(searchContext):
    phrase = []
    remain = []
    # print(searchContext)
    pos = 0
    lastpos = 0
    for i in range(len(searchContext)):
        if i < pos:
            continue
        if searchContext[i] == "“":
            pos = checkRightPos(searchContext, i + 1)
            if pos != -1:
                # print(pos)
                if i != 0:
                    remain.append(searchContext[lastpos:i + 1])
                lastpos = pos + 1
                phrase.append(searchContext[i + 1:pos])
    remain.append(searchContext[lastpos:len(searchContext)])
    # print(phrase)
    # print(remain)
    return phrase


# 检索右边双引号的索引下标
def checkRightPos(searchContext, left):
    for i in range(len(searchContext) - left):
        if searchContext[left + i] == "”":
            # print(left+i)
            return left + i
    return -1


# 短语检索
def phraseCheck(phrase,indexfile):
    # print(phrase)
    # 进行分词
    result = list(jieba.cut_for_search(phrase))
    result = process(result)
    # print(result)
    # 读取倒排索引表
    with open(indexfile, "rb") as file:
        indexfile = json.load(file)
        # print(indexfile)
    wordlist = list(indexfile.keys())
    # print(wordlist)

    # 检索各个短语是否位于倒排索引表中
    poslist = []
    for i in range(len(result)):
        if result[i] in wordlist:
            # print(result[i])
            pos = wordlist.index(result[i])
            poslist.append(pos)
        else:
            # 不存在该短语，返回-1
            return (-1)
    # print(poslist)

    # 获取各个索引词的文件列表
    doclist = dict()
    for i in range(len(poslist)):
        doclist[result[i]] = indexfile[result[i]]

    # 获取公共出现的文件列表
    doclist = findSameFile(doclist)
    # print(doclist)

    # 获取短语所在的文件及出现位置
    result = check(doclist, result, indexfile)
    # print(result)
    return result


# 获取短语所在的文件及出现位置
def check(doclist, result, indexfile):
    posdict = []
    # 构建检索用的字典，词，文章，位置
    for i in range(len(result)):
        temp = dict()
        for j in range(len(doclist)):
            temp[doclist[j]] = indexfile[result[i]][doclist[j]]
        posdict.append(temp)
    # print(posdict)

    result = dict()
    sig = 0
    poslist = list(posdict[0].values())
    doclist = list(posdict[0].keys())
    for i in range(len(posdict[0].keys())):  # 先按文章搜索
        allpos = poslist[i]
        docid = doclist[i]
        for j in range(len(allpos)):  # 第一个词在文章中的各个位置
            num = allpos[j]
            flag = 0
            for k in range(len(posdict) - 1):  # 剩余词在该文章中的位置
                pos1 = posdict[k + 1][docid]
                if num + 1 not in pos1:
                    flag = 1
                    break
                else:
                    num = num + 1
            if flag == 0:
                result[docid] = allpos[j]
                sig = 1
            else:
                flag = 0
    if sig == 1:
        return result
    else:
        return -1


# 获取公共文章列表
def findSameFile(doclist):
    list1 = list(doclist.values())
    filelist = []
    for item in list1:
        filelist.append(list(item.keys()))

    set1 = set(filelist[0])
    for i in range(len(filelist) - 1):
        set2 = set(filelist[i + 1])
        set1 = set1 & set2
    return (list(set1))


# 去除结巴保留的短语
def process(cutlist):
    trash = []
    for i in range(len(cutlist) - 1):
        for j in range(len(cutlist) - i - 1):
            if cutlist[i] in cutlist[j + i + 1]:
                trash.append(j + i + 1)
    trash = list(set(trash))
    # print(trash)
    for i in range(len(trash)):
        cutlist.pop(trash[i])
        for j in range(len(trash) - i - 1):
            trash[i + j + 1] = trash[i + j + 1] - 1
    # print(cutlist)
    return cutlist


# 短语检索函数（用这个！！！）
# 如果没有短语，返回空列表
# 如果没有匹配结果，返回列表中的元素为-1
def phraseSearch(phraselist,indexfile):
    # print(phraselist)
    resultlist = []
    for item in phraselist:
        result = phraseCheck(item,indexfile)
        resultlist.append(result)
    # print(resultlist)
    return resultlist

# phraseSearch("[“上海复旦大学”]")
# phraseSearch("“预警系统”的微博“活跃用户”")
# phraseSearch("预警系统的微博的活跃用户")